<script setup>
	import { ref, onMounted } from 'vue'
	import { useUserStore } from '@/store/userInfo'
	import { useCartStore } from '@/store/cart'
	import { useShopStore } from '@/store/shop'

	const userStore = useUserStore( )
	const cartStore = useCartStore( )
	const shopStore = useShopStore( )
	const orderApi = uniCloud.importObject( 'order' )
	const goPay = ref( null )

	// 订单状态常量
	const ORDER_STATES = [ '全部', '待付款', '待发货', '待收货', '已完成' ]

	// 订单数据
	const orderDetail = ref( null )

	// 获取订单详情
	const getOrderDetail = async ( orderId ) => {
		try {
			const result = await orderApi.getOrderList( userStore.userInfo.uid )
			if ( result.errCode === 0 ) {
				const order = result.data.find( item => item._id === orderId )
				if ( order ) {
					orderDetail.value = order
				} else {
					uni.showToast( {
						title: '订单不存在',
						icon: 'none'
					} )
					setTimeout( ( ) => {
						uni.navigateBack( )
					}, 1500 )
				}
			}
		} catch ( e ) {
			uni.showToast( {
				title: '获取订单详情失败',
				icon: 'none'
			} )
		}
	}

	// 计算倒计时时间（分钟）
	const getCountdownMinutes = ( createTime ) => {
		const now = Date.now( )
		const deadline = createTime + ( 10 * 60 * 1000 ) // 10分钟期限
		const remaining = Math.max( 0, deadline - now )
		return Math.floor( remaining / ( 1000 * 60 ) )
	}

	// 倒计时结束处理
	const timeup = async ( order_no ) => {
		try {
			const result = await orderApi.deleteOrder( order_no )
			if ( result.errCode === 0 ) {
				uni.showToast( {
					title: '订单已超时自动取消',
					icon: 'none'
				} )
				setTimeout( ( ) => {
					uni.navigateBack( )
				}, 1500 )
			}
		} catch ( error ) {
			console.error( '删除超时订单失败:', error )
		}
	}

	// 取消订单
	const cancelOrder = ( order_no ) => {
		uni.showModal( {
			title: '提示',
			content: '确定要取消该订单吗？',
			success: async ( res ) => {
				if ( res.confirm ) {
					try {
						const result = await orderApi.deleteOrder( order_no )
						if ( result.errCode === 0 ) {
							uni.showToast( {
								title: '订单已取消',
								icon: 'success'
							} )
							setTimeout( ( ) => {
								uni.navigateBack( )
							}, 1500 )
						}
					} catch ( error ) {
						uni.showToast( {
							title: '取消订单失败',
							icon: 'none'
						} )
					}
				}
			}
		} )
	}

	// 确认收货
	const confirmReceive = ( order_no ) => {
		uni.showModal( {
			title: '提示',
			content: '确认已收到商品？',
			success: async ( res ) => {
				if ( res.confirm ) {
					try {
						const result = await orderApi.updateOrderState( order_no, 4 )
						if ( result.errCode === 0 ) {
							uni.showToast( {
								title: '确认收货成功',
								icon: 'success'
							} )
							getOrderDetail( orderDetail.value._id )
						}
					} catch ( error ) {
						uni.showToast( {
							title: '确认收货失败',
							icon: 'none'
						} )
					}
				}
			}
		} )
	}

	// 继续支付
	const openPay = async ( orderData ) => {
		await goPay.value.createOrder( {
			order_no: orderData.order_no,
			provider: 'wxpay',
			total_fee: orderData.tatalPrice * 100, // 转换为分为单位
			type: 'goods',
			description: '商品订单'
		} )
	}

	// 再次购买
	const againPay = async ( lastOrderData ) => {
		const orderData = {
			cart_list: lastOrderData.cart_list,
			address: lastOrderData.address,
			recipient: lastOrderData.recipient,
			recipientMobile: lastOrderData.recipientMobile,
			tatalPrice: lastOrderData.tatalPrice,
			num: lastOrderData.num,
			state: 1
		}

		const result = await orderApi.add( userStore.userInfo.uid, orderData )
		const resPay = await goPay.value.createOrder( {
			order_no: result.order_no,
			provider: 'wxpay',
			total_fee: lastOrderData.tatalPrice * 100, // 转换为分为单位
			type: 'goods',
			description: '小圆星店商品订单'
		} )
	}

	// 支付成功
	const onSuccess = ( res ) => {
		console.log( '支付成功', res )
		cartStore.clearCart( )
		setTimeout( ( ) => {
			uni.navigateBack( )
		}, 1500 )
	}

	// 支付取消
	const onCancel = ( res ) => {
		uni.showToast( {
			icon: "none",
			title: "取消支付",
			mask: true
		} )
	}

	// 返回上一页
	const goBack = ( ) => {
		uni.navigateBack( )
	}

	onMounted( ( ) => {
		// 获取页面参数
		const pages = getCurrentPages( )
		const currentPage = pages[ pages.length - 1 ]
		const orderId = currentPage.options.orderId

		if ( orderId ) {
			getOrderDetail( orderId )
		} else {
			uni.showToast( {
				title: '订单ID不存在',
				icon: 'none'
			} )
			setTimeout( ( ) => {
				uni.navigateBack( )
			}, 1500 )
		}
	} )
</script>
<template>
	<view class="order-detail-container" v-if="orderDetail">
		<view class="order-detail"
			:style="{ paddingBottom: 'calc(140rpx + env(safe-area-inset-bottom))' }">
			<view class="orderInfo">
				<!-- 商家标题 -->
				<view class="title">
					<text class="shop-name">{{shopStore.shopInfo.shop_name}}</text>
					<text class="status" :class="{
						'wait-pay': orderDetail.state === 1,
						'wait-send': orderDetail.state === 2,
						'wait-receive': orderDetail.state === 3,
						'completed': orderDetail.state === 4
					}">{{ ORDER_STATES[orderDetail.state] }}</text>
				</view>

				<!-- 订单信息 -->
				<view class="order-base-info">
					<view class="info-item">
						<text class="label">下单时间：</text>
						<uni-dateformat class="value" :date="orderDetail.create_time"></uni-dateformat>
					</view>
					<view class="info-item">
						<text class="label">订单编号：</text>
						<text class="value">{{ orderDetail.order_no }}</text>
						<text class="copy">复制</text>
					</view>
				</view>

				<!-- 商品信息 -->
				<view class="goods-info">
					<view class="goods-list">
						<view class="goods-item" v-for="goods in orderDetail.cart_list" :key="goods._id">
							<!-- 产品封面 -->
							<view class="cover">
								<image :src="goods.cover_pic" mode="aspectFill"></image>
							</view>
							<!-- 产品信息 -->
							<view class="info">
								<view class="name">{{goods.name}}</view>
								<view class="sku" v-if="goods.spec">规格：{{goods.spec}}</view>
								<view class="buy-price">单价：￥{{goods.buy_price}}/份</view>
								<view class="num">数量：{{goods.num}}</view>
							</view>
						</view>
					</view>
					<!-- 底部合计信息总件数和总价 -->
					<view class="total-bottom">
						<text class="count">共 {{orderDetail.num}} 件</text>
						<text class="label">小计:</text>
						<text class="price">￥{{Number(orderDetail.tatalPrice).toFixed(2)}}</text>
					</view>
				</view>

				<!-- 价格明细 -->
				<view class="price-detail">
					<view class="price-item">
						<text>运费</text>
						<text>¥{{ Number(0).toFixed(2) }}</text>
					</view>
					<view class="price-item total">
						<text>应付合计</text>
						<text class="total-price">¥{{ Number(orderDetail.tatalPrice).toFixed(2) }}</text>
					</view>
				</view>

				<!-- 底部按钮 - 根据不同状态显示不同按钮 -->
				<view class="footer">
					<view class="btn-group">
						<!-- 待付款状态 -->
						<template v-if="orderDetail.state === 1">
							<button class="btn cancel" @tap="cancelOrder(orderDetail.order_no)">取消订单</button>
							<button class="btn pay" @tap="openPay(orderDetail)">继续支付</button>
						</template>
						<!-- 待发货状态 -->
						<template v-if="orderDetail.state === 2">
							<button class="btn cancel" @tap="goBack">返回</button>
						</template>
						<!-- 待收货状态 -->
						<template v-if="orderDetail.state === 3">
							<button class="btn confirm" @tap="confirmReceive(orderDetail.order_no)">确认收货</button>
						</template>
						<!-- 已完成状态 -->
						<template v-if="orderDetail.state === 4">
							<button class="btn rebuy" @tap="againPay(orderDetail)">再次购买</button>
						</template>
					</view>
					<!-- 底部安全区域占位 -->
					<view class="safe-area-inset-bottom"></view>
				</view>

				<!-- 支付组件 -->
				<uni-pay ref="goPay" @success="onSuccess" @fail="onCancel" />
			</view>
		</view>
	</view>
</template>


<style lang="scss" scoped>
	.order-detail-container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.order-detail {
		padding: 24rpx;
		// 移除之前的margin-bottom，改用padding-bottom
		margin-bottom: 120rpx;

		.orderInfo {
			padding: 16rpx 24rpx;
			background-color: #fff;
			border-radius: 24rpx;

			/*商家店名和状态*/
			.title {
				padding-bottom: 16rpx;
				border-bottom: 1px solid $line-color-aux;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.shop-name {
					@include shopName;
				}

				.status {
					font-size: 28rpx;

					// 订单状态颜色
					&.wait-pay {
						color: #ff4d4f; // 待付款-红色
					}

					&.wait-send {
						color: #faad14; // 待发货-橙色
					}

					&.wait-receive {
						color: #1890ff; // 待收货-蓝色
					}

					&.completed {
						color: #52c41a; // 已完成-绿色
					}
				}
			}

			/*订单基本信息*/
			.order-base-info {
				padding: 24rpx 0;
				border-bottom: 1px solid $line-color-aux;

				.info-item {
					display: flex;
					align-items: center;
					font-size: 24rpx;
					color: $text-font-color-3;
					margin-bottom: 12rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.label {
						min-width: 140rpx;
					}

					.value {
						flex: 1;
					}

					.copy {
						color: #1890ff;
						margin-left: 20rpx;
					}
				}
			}
		}

		.goods-info {
			margin-top: 20rpx;
			background-color: #fff;
			padding: 24rpx;

			.goods-list {
				.goods-item {
					display: flex;
					padding-bottom: 24rpx;

					.cover {
						image {
							width: 140rpx;
							height: 140rpx;
							border-radius: 8rpx;
						}
					}

					.info {
						flex: 1;
						margin-left: 20rpx;
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.name {
							font-size: 28rpx;
							color: #333;
						}

						.sku {
							font-size: 24rpx;
							color: #999;
						}

						.buy-price {
							font-size: 24rpx;
							color: #666;
						}

						.num {
							font-size: 24rpx;
							color: #666;
						}
					}
				}
			}

			.total-bottom {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				padding-top: 24rpx;
				border-top: 2rpx solid #f5f5f5;

				.count {
					font-size: 28rpx;
					color: #999;
				}

				.label {
					font-size: 24rpx;
					color: #333;
					margin: 0 8rpx;
				}

				.price {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}
			}
		}

		.price-detail {
			margin-top: 20rpx;
			background-color: #fff;
			padding: 24rpx;

			.price-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;
				font-size: 28rpx;
				color: #666;

				&.total {
					margin-top: 20rpx;
					padding-top: 20rpx;
					border-top: 2rpx solid #f5f5f5;

					.total-price {
						color: #333;
						font-weight: bold;
					}
				}
			}
		}

		.order-note {
			margin-top: 20rpx;
			background-color: #fff;
			padding: 24rpx;
			display: flex;
			align-items: center;

			.label {
				font-size: 28rpx;
				color: #666;
				margin-right: 20rpx;
			}

			.value {
				font-size: 28rpx;
				color: #333;
			}
		}

		.footer {
			@include pageBtnStyle;
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: #fff;
			width: 100%;
			z-index: 99;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

			.btn-group {
				display: flex;
				justify-content: flex-end;

				.btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					margin-left: 24rpx;
					font-size: 28rpx;
					border-radius: 48rpx;
					font-weight: bold;

					&:first-child {
						margin-left: 0;
					}

					/* 取消按钮样式 */
					&.cancel {
						color: #666;
						background-color: #fff;
						border: 1px solid #ddd;
					}

					/* 支付按钮样式 */
					&.pay {
						color: #fff;
						background-color: $brand-theme-color;
						border: none;
					}

					/* 确认收货按钮样式 */
					&.confirm {
						color: #fff;
						background-color: $brand-theme-color;
						border: none;
					}

					/* 再次购买按钮样式 */
					&.rebuy {
						color: #fff;
						background-color: $brand-theme-color;
						border: none;
					}

					/* 添加点击效果 */
					&:active {
						opacity: 0.8;
					}
				}
			}

			/* 底部安全区域 */
			.safe-area-inset-bottom {
				width: 100%;
				height: env(safe-area-inset-bottom);
				background-color: #fff;
			}
		}
	}

	/* 适配 iOS 底部安全区域 */
	@supports (padding-bottom: constant(safe-area-inset-bottom)) {
		.order-detail {
			padding-bottom: calc(140rpx + constant(safe-area-inset-bottom));
		}
	}

	@supports (padding-bottom: env(safe-area-inset-bottom)) {
		.order-detail {
			padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
		}
	}
</style>